<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    width="650"
    placement="right"
    :closable="true"
    @close="close"
    :visible="visible"
    style="overflow: auto; padding-bottom: 53px"
  >
    <a-form>
      <a-form-item :label="$t('所拥有的权限')">
        <a-tree
          checkable
          :checkedKeys="checkedKeys"
          :treeData="treeData"
          :selectedKeys="selectedKeys"
          :expandedKeys="expandedKeysss"
          :checkStrictly="checkStrictly"
          @check="onCheck"
          @expand="onExpand"
          @select="onTreeNodeSelect"
        >
          <span slot="hasDatarule" slot-scope="{ slotTitle, ruleFlag }">
            {{ slotTitle }}<a-icon v-if="ruleFlag" type="align-left" style="margin-left: 5px; color: red"></a-icon>
            <a-tooltip>
              <template slot="title">{{
                $t(
                  '勾选该权限则表明具有此业务权限，即进行该业务的时候无需授权可直接进行；反之取消勾选则表明无此业务权限，若需进行此业务的时候需要具有此权限的人授权后方可进行。'
                )
              }}</template>
              <a-icon type="question-circle" v-if="slotTitle == $t('业务授权')" style="margin-left: 5px" />
            </a-tooltip>
            <a-tooltip>
              <template slot="title">{{
                $t(
                  '某些特殊商品不想要吧员直接售卖，需要授权才允许销售时可使用“商品授权”功能；新增商品时设置为“授权销售”的商品在销售时若具有“商品授权”功能的操作员则可直接销售，否则销售时会弹出让管理员授权，选择具有“商品授权”功能的操作员授权后即可正常销售。'
                )
              }}</template>
              <a-icon type="question-circle" v-if="slotTitle == $t('商品授权')" style="margin-left: 5px" />
            </a-tooltip>
          </span>
        </a-tree>
      </a-form-item>
    </a-form>

    <div class="drawer-bootom-button">
      <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="switchCheckStrictly(1)">{{ $t('父子关联') }}</a-menu-item>
          <a-menu-item key="2" @click="switchCheckStrictly(2)">{{ $t('取消关联') }}</a-menu-item>
          <a-menu-item key="3" @click="checkALL">{{ $t('全部勾选') }}</a-menu-item>
          <a-menu-item key="4" @click="cancelCheckALL">{{ $t('取消全选') }}</a-menu-item>
          <a-menu-item key="5" @click="expandAll">{{ $t('展开所有') }}</a-menu-item>
          <a-menu-item key="6" @click="closeAll">{{ $t('合并所有') }}</a-menu-item>
        </a-menu>
        <a-button> {{ $t('树操作') }} <a-icon type="up" /> </a-button>
      </a-dropdown>
      <a-popconfirm :title="$t('确定放弃编辑？')" @confirm="close" :okText="$t('确定')" :cancelText="$t('取消')">
        <a-button style="margin-right: 0.8rem">{{ $t('取消') }}</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit(false)" type="primary" :loading="loading" ghost style="margin-right: 0.8rem">{{
        $t('仅保存')
      }}</a-button>
      <a-button @click="handleSubmit(true)" type="primary" :loading="loading">{{ $t('保存并关闭') }}</a-button>
    </div>

    <role-datarule-modal ref="datarule"></role-datarule-modal>
  </a-drawer>
</template>
<script>
import { queryTreeListForRole, queryRolePermission, saveRolePermission } from '@/api/api'
import RoleDataruleModal from './RoleDataruleModal.vue'

export default {
  name: 'RoleModal',
  components: {
    RoleDataruleModal,
  },
  data() {
    return {
      roleId: '',
      treeData: [],
      defaultCheckedKeys: [],
      checkedKeys: [],
      expandedKeysss: [],
      allTreeKeys: [],
      autoExpandParent: true,
      checkStrictly: true,
      title: this.$t('角色权限配置'),
      visible: false,
      loading: false,
      selectedKeys: [],
    }
  },
  methods: {
    onTreeNodeSelect(id) {
      if (id && id.length > 0) {
        this.selectedKeys = id
      }
      this.$refs.datarule.show(this.selectedKeys[0], this.roleId)
    },
    onCheck(o, e) {
      if (e.node.$children) {
        if(e.checked && !this.expandedKeysss.includes(e.node.eventKey)){
          this.expandedKeysss = [...this.expandedKeysss, e.node.eventKey]
        }
        if(!e.checked && this.expandedKeysss.includes(e.node.eventKey)){
          this.expandedKeysss = this.expandedKeysss.filter(c => c != e.node.eventKey)
        }
      }
      if(this.checkStrictly){
        this.checkedKeys = o.checked.filter((c) => {
          return (c != e.node.value && !e.checked) || e.checked
        })
      }else{
        this.checkedKeys = o
      }
      /* if (this.checkStrictly) {
        this.halfCheckedKeys = []
        this.checkedKeys = o.checked.filter((c) => {
          return (c != e.node.value && !e.checked) || e.checked
        })
      } else {
        this.halfCheckedKeys = e.halfCheckedKeys
        this.checkedKeys = o
      } */
    },
    show(roleId) {
      this.roleId = roleId
      this.visible = true
    },
    close() {
      this.reset()
      this.$emit('close')
      this.visible = false
    },
    onExpand(expandedKeys) {
      this.expandedKeysss = expandedKeys
      this.autoExpandParent = false
    },
    reset() {
      this.expandedKeysss = []
      this.checkedKeys = []
      this.defaultCheckedKeys = []
      this.loading = false
    },
    expandAll() {
      this.expandedKeysss = this.allTreeKeys
    },
    closeAll() {
      this.expandedKeysss = []
    },
    checkALL() {
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckALL() {
      this.checkedKeys = []
    },
    switchCheckStrictly(v) {
      if (v == 1) {
        this.checkStrictly = false
      } else if (v == 2) {
        this.checkStrictly = true
      }
    },
    handleCancel() {
      this.close()
    },
    handleSubmit(exit) {
      let that = this
      let params = {
        roleId: that.roleId,
        permissionIds: that.checkedKeys.join(','),
        lastpermissionIds: that.defaultCheckedKeys.join(','),
      }
      that.loading = true
      saveRolePermission(params).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loading = false
          if (exit) {
            that.close()
          }
        } else {
          that.$message.error(res.message)
          that.loading = false
          if (exit) {
            that.close()
          }
        }
        that.loadData()
      })
    },
    loadData() {
      queryTreeListForRole().then((res) => {
        this.treeData = res.result.treeList
        this.allTreeKeys = res.result.ids
        queryRolePermission({roleId:this.roleId}).then((res)=>{
          this.checkedKeys = [...res.result];
          this.defaultCheckedKeys = [...res.result];
          this.expandedKeysss = [];
        })
      })
    },
  },
  watch: {
    visible() {
      if (this.visible) {
        this.loadData()
      }
    },
  },
}
</script>
<style lang="less" scoped>
.drawer-bootom-button {
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>